//
//  YiDaLocation.swift
//  YiDa
//
//  Created by zhoufei on 16/6/26.
//  Copyright © 2016年 ZhouFei. All rights reserved.
//

import UIKit
import CoreLocation
typealias locationFaileBlock = ()->Void
class YiDaLocationManager: NSObject,CLLocationManagerDelegate {
    var locManager:CLLocationManager?
    var locationFaile:locationFaileBlock?
    class var main:YiDaLocationManager{
        struct Static {
            static let instance:YiDaLocationManager = YiDaLocationManager()
        }
        return Static.instance
    }
    
    override init() {
        super.init()
        
        
        
        locManager = CLLocationManager()
        locManager?.delegate = self
        locManager?.desiredAccuracy = kCLLocationAccuracyBest
        locManager?.distanceFilter = 5.0
        locManager?.requestWhenInUseAuthorization()
        locManager?.startUpdatingLocation()
    }
    
    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        
        
        let geocoder = CLGeocoder()
        let currentLocation = CLLocation(latitude: newLocation.coordinate.latitude, longitude: newLocation.coordinate.longitude)
        geocoder.reverseGeocodeLocation(currentLocation, completionHandler: {
            (placemarks:[CLPlacemark]?, error:NSError?) -> Void in
            
            YiDaLocation.main.lat = newLocation.coordinate.latitude
            YiDaLocation.main.lng = newLocation.coordinate.longitude
            //强制转成简体中文
            let array = NSArray(object: "zh-hans")
            NSUserDefaults.standardUserDefaults().setObject(array, forKey: "AppleLanguages")
            //显示所有信息
            if error != nil {
                self.saveLocation()
                return
            }
            
            if let p = placemarks?[0]{
                YiDaLocation.main.address = p.country! + p.locality! + p.thoroughfare!
                self.saveLocation()
            } else {
                self.saveLocation()
            }
        })

        
    }
    
    func saveLocation(){
        YiDaLocation.main.saveDefault()
    }
    
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("error")
        if  locationFaile != nil{
            self.locationFaile!()
        }
    }
}
